/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package processor;

import entity.Articles;
import entity.Members;
import java.util.Calendar;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author maynoigi
 */
@Stateless
public class ArticlesFacade extends AbstractFacade<Articles> {
    @PersistenceContext(unitName = "ManTechHelpdesk-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public ArticlesFacade() {
        super(Articles.class);
    }
     public List<Articles> getArticlesAll() {
        return em.createQuery("SELECT a from Articles a ORDER BY a.articlesId DESC").getResultList();
    }

    public List<Articles> getArticlesByCount(Integer count) {
        return em.createQuery("SELECT a from Articles a ORDER BY a.articlesId DESC").setMaxResults(count).getResultList();
    }

    public Articles getArticlesByArticlesID(int ID) {
        return (Articles) em.createNamedQuery("Articles.findByArticlesId").setParameter("articlesId", ID).getSingleResult();
    }
    
    public boolean createArticle(String title,String content,Calendar createDate,Members members) {
        try {
            Articles ar = new Articles();
            ar.setArticlesTitle(title);
            ar.setArticlesContent(content);
            ar.setArticlesCreateDate(createDate.getTime());
            ar.setMembersID(members);
            em.persist(ar);
            return true;
        } catch(EntityExistsException e){
            System.out.println(e.getMessage());
            return false;
        } catch(Exception e){
            System.out.println(e.getMessage());
            return false;
        }
    }
    
    public boolean editArticle(Integer articleID,String articleTitle,String articleContent,Calendar createDate,Members members) {
        try {
            Articles ar = new Articles(articleID);
            ar.setArticlesTitle(articleTitle);
            ar.setArticlesContent(articleContent);
            ar.setArticlesCreateDate(createDate.getTime());
            ar.setMembersID(members);
            em.merge(ar);
            return true;
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
            return false;
        } catch(Exception e){
            System.out.println(e.getMessage());
            return false;
        }
    } 
    
    public boolean removeArticle(Integer articleID){
        try {
            Articles ar = getArticlesByArticlesID(articleID);
            em.remove(ar);
            return true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        }
    }
 
}
